// 用户购物车仓库
import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import {
  useGetShoppingCartListService,
  useUpdateShoppingCartService,
  useDelShoppingCartService
} from '@/api/requsets/index.js'

export const useShoppingCartStore = defineStore(
  'useShoppingCartStore',
  () => {
    // 用户购物车列表
    const shoppingCartList = ref([])

    // 购物车商品被选中总数
    const checkTotal = computed(() => {
      return shoppingCartList.value.reduce((sum, item) => {
        if (item.is_checked) sum += item.goods_num
        return sum
      }, 0)
    })

    // 购物车商品总数
    const total = ref()

    // 被勾选总价
    const totalPrice = computed(() => {
      return shoppingCartList.value
        .reduce((sum, item) => {
          if (item.is_checked) {
            sum += item.goods_num * item.goods.goods_price_min
          }
          return sum
        }, 0)
        .toFixed(2)
    })

    // 获取购物车数据
    const getShoppingCartData = async () => {
      const {
        data: { list, cartTotal }
      } = await useGetShoppingCartListService()
      shoppingCartList.value = list.map((item) => {
        item.is_checked = true
        return item
      })
      total.value = cartTotal
    }

    // 购物车全选反选
    const handleCheckAll = async (isSelect, isEdit = false) => {
      if (isSelect) {
        console.log('勾选', isSelect)
        shoppingCartList.value = shoppingCartList.value.map((item) => {
          item.is_checked = true
          return item
        })
      } else {
        console.log('取消勾选', isSelect)
        shoppingCartList.value = shoppingCartList.value.map((item) => {
          item.is_checked = false
          return item
        })
      }
    }

    // 处理购物车数量的回调
    const handleCount = async (data, choose) => {
      console.log('count')
      if (choose === 'sub') {
        if (data.goods_num === 1) return
        // data.goods_num--
        shoppingCartList.value = shoppingCartList.value.map((item) => {
          if (item.goods_id === data.goods_id) {
            item.goods_num -= 1
          }
          return item
        })
      } else {
        // data.goods_num++
        shoppingCartList.value = shoppingCartList.value.map((item) => {
          if (item.goods_id === data.goods_id) {
            item.goods_num += 1
          }
          return item
        })
      }
      await useUpdateShoppingCartService({
        goodsId: data.goods_id,
        goodsNum: data.goods_num,
        goodsSkuId: '0'
      })
    }
    const temp = ref([])
    //数据备份
    const backupData = (data) => {
      temp.value = JSON.parse(JSON.stringify(data))
    }

    // 数据回滚
    const rollBack = () => {
      shoppingCartList.value = temp.value
    }

    // 删除购物车商品
    const handleDel = async () => {
      const cartIds = shoppingCartList.value
        .filter((item) => item.is_checked)
        .map((item) => item.id)

      await useDelShoppingCartService({ cartIds })

      await getShoppingCartData()
    }
    watch(
      shoppingCartList,
      (newVal, oldValue) => {
        console.log(newVal, oldValue)
      },
      {
        deep: true
      }
    )
    // 用户退出清除购物车
    const clearShoppingCart = () => {
      shoppingCartList.value = []
      total.value = 0
    }

    return {
      shoppingCartList,
      total,
      totalPrice,
      getShoppingCartData,
      handleCheckAll,
      handleCount,
      checkTotal,
      backupData,
      rollBack,
      handleDel,
      clearShoppingCart
    }
  },
  {
    persist: true
  }
)
